package com.sddnytsh.body_buildingsystem.screens

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.Profile
import com.sddnytsh.body_buildingsystem.services.AvatarService
import com.sddnytsh.body_buildingsystem.components.AvatarSelector
import coil.Coil
import coil.memory.MemoryCache
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

@Composable
fun ProfileScreen(navController: NavController) {
    /* 省略变量声明，与之前相同 */
    // 使用UserState中的用户信息
    val currentUser = UserState.currentUser
    val userId = currentUser?.id ?: 1L
    var userName by remember { mutableStateOf(currentUser?.username ?: "默认名字") }
    var userBio by remember { mutableStateOf("默认签名") }
    var userHeight by remember { mutableStateOf(170) }
    var userWeight by remember { mutableStateOf(60) }
    var userBirthday by remember { mutableStateOf("1990-01-01") }
    var tempGender by remember { mutableStateOf("男") }
    var tempRegion by remember { mutableStateOf("江苏 南京") }
    var userAvatar by remember { mutableStateOf<String?>(null) } // 头像URL
    var refreshKey by remember { mutableStateOf(0) } // 强制刷新键

    /* 对话框开关 */
    var showNameDialog by remember { mutableStateOf(false) }
    var showBioDialog by remember { mutableStateOf(false) }
    var showHeightDialog by remember { mutableStateOf(false) }
    var showWeightDialog by remember { mutableStateOf(false) }
    var showBirthdayDialog by remember { mutableStateOf(false) }
    var showGenderDialog by remember { mutableStateOf(false) }
    var showRegionDialog by remember { mutableStateOf(false) }

    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    val avatarService = remember { AvatarService(context) }

    /* 进入页面时拉最新数据 */
    LaunchedEffect(Unit) {
        fetchProfileData(userId)?.let {
            userName   = it.name
            userBio    = it.des
            userHeight = it.height.toInt()
            userWeight = it.weight.toInt()
            userBirthday = it.birthday
            tempGender = it.gender
            tempRegion = it.location
            userAvatar = it.avatar // 设置头像URL
            UserState.updateUserAvatar(it.avatar)  // 同步更新全局状态
        }
    }

    /* 统一保存函数 */
    fun saveAll() {
        val profile = Profile(
            userId   = userId,
            name     = userName,
            des      = userBio,
            avatar   = userAvatar, // 包含头像URL
            gender   = tempGender,
            height   = userHeight.toDouble(),
            weight   = userWeight.toDouble(),
            birthday = userBirthday,
            location = tempRegion
        )
        coroutineScope.launch { updateProfile(profile, context) }
    }
    
    /* 头像选择处理 */
    fun handleAvatarSelected(bitmap: Bitmap) {
        Log.e("ProfileScreen", "🔥 handleAvatarSelected被调用！bitmap尺寸: ${bitmap.width}x${bitmap.height}")
        coroutineScope.launch {
            try {
                val result = avatarService.uploadAvatar(userId, bitmap)
                result.fold(
                    onSuccess = { avatarUrl ->
                        Log.d("ProfileScreen", "头像上传成功，新URL: $avatarUrl")
                        Log.d("ProfileScreen", "更新前userAvatar: $userAvatar")
                        
                        // 🔥 1. 给URL加时间戳，让Coil认为是新图
                        val noCacheUrl = "${avatarUrl}?t=${System.currentTimeMillis()}"
                        Log.d("ProfileScreen", "使用无缓存URL: $noCacheUrl")
                        
                        // 🔥 2. 手动清掉Coil内存缓存（磁盘不用管，URL已变）
                        try {
                            Coil.imageLoader(context).memoryCache?.remove(MemoryCache.Key(avatarUrl))
                            Log.d("ProfileScreen", "Coil内存缓存已清空")
                        } catch (e: Exception) {
                            Log.e("ProfileScreen", "清内存缓存失败: ${e.message}")
                        }
                        
                        // 🔥 3. 刷新UI
                        userAvatar = noCacheUrl
                        UserState.updateUserAvatar(noCacheUrl)  // 同步更新全局状态
                        Log.d("ProfileScreen", "更新后userAvatar: $userAvatar")
                        
                        // 保存包含头像的完整信息
                        saveAll()
                        
                        Toast.makeText(context, "头像上传成功", Toast.LENGTH_SHORT).show()
                    },
                    onFailure = { error ->
                        Toast.makeText(context, "头像上传失败: ${error.message}", Toast.LENGTH_SHORT).show()
                    }
                )
            } catch (e: Exception) {
                Toast.makeText(context, "头像上传异常: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /* 测试上传功能 */
    fun testUpload() {
        coroutineScope.launch {
            try {
                val result = avatarService.testUpload(userId)
                result.fold(
                    onSuccess = { avatarUrl ->
                        Log.d("ProfileScreen", "测试上传成功，新URL: $avatarUrl")
                        Log.d("ProfileScreen", "更新前userAvatar: $userAvatar")
                        
                        // 🔥 1. 给URL加时间戳，让Coil认为是新图
                        val noCacheUrl = "${avatarUrl}?t=${System.currentTimeMillis()}"
                        Log.d("ProfileScreen", "使用无缓存URL: $noCacheUrl")
                        
                        // 🔥 2. 手动清掉Coil内存缓存（磁盘不用管，URL已变）
                        try {
                            Coil.imageLoader(context).memoryCache?.remove(MemoryCache.Key(avatarUrl))
                            Log.d("ProfileScreen", "Coil内存缓存已清空")
                        } catch (e: Exception) {
                            Log.e("ProfileScreen", "清内存缓存失败: ${e.message}")
                        }
                        
                        // 🔥 3. 刷新UI
                        userAvatar = noCacheUrl
                        Log.d("ProfileScreen", "更新后userAvatar: $userAvatar")
                        
                        // 保存到服务器
                        saveAll()
                        
                        Toast.makeText(context, "测试上传成功: $avatarUrl", Toast.LENGTH_LONG).show()
                    },
                    onFailure = { error ->
                        Toast.makeText(context, "测试上传失败: ${error.message}", Toast.LENGTH_LONG).show()
                    }
                )
            } catch (e: Exception) {
                Toast.makeText(context, "测试上传异常: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                contentDescription = "返回",
                modifier = Modifier
                    .size(24.dp)
                    .clickable { navController.popBackStack() }
            )
            Spacer(Modifier.width(8.dp))
            Text("个人资料", style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold))
        }

        Spacer(Modifier.height(16.dp))

        // 头像选择器 - 使用refreshKey强制刷新
        AvatarSelector(
            currentAvatar = userAvatar,
            currentName = userName,
            onAvatarSelected = { bitmap -> handleAvatarSelected(bitmap) },
            onDefaultAvatarSelected = { avatarUrl -> 
                userAvatar = avatarUrl
                UserState.updateUserAvatar(avatarUrl)  // 同步更新全局状态
                saveAll()
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp)
        )

        Spacer(Modifier.height(16.dp))

        ProfileItem2("名字", userName) { showNameDialog = true }
        ProfileItem2("性别", tempGender) { showGenderDialog = true }
        ProfileItem2("地区", tempRegion) { showRegionDialog = true }
        ProfileItem2("签名", userBio) { showBioDialog = true }
        ProfileItem2("身高", userHeight) { showHeightDialog = true }
        ProfileItem2("体重", userWeight) { showWeightDialog = true }
        ProfileItem2("生日", userBirthday) { showBirthdayDialog = true }
        
        // 测试按钮
        Button(
            onClick = { testUpload() },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
        ) {
            Text("测试头像上传")
        }
        
        // 强制刷新头像按钮
        Button(
            onClick = { 
                Log.d("ProfileScreen", "强制刷新头像 - 当前userAvatar: $userAvatar")
                Log.e("ProfileScreen", "强制刷新头像 - 当前userAvatar: $userAvatar") // 使用ERROR级别确保显示
                userAvatar = null
                kotlinx.coroutines.GlobalScope.launch {
                    kotlinx.coroutines.delay(100)
                    fetchProfileData(userId)?.let {
                        userAvatar = it.avatar
                        Log.d("ProfileScreen", "重新获取头像URL: ${it.avatar}")
                        Log.e("ProfileScreen", "重新获取头像URL: ${it.avatar}") // 使用ERROR级别确保显示
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
        ) {
            Text("强制刷新头像")
        }
    }

    /* 名字 */
    if (showNameDialog) EditTextDialog(
        title = "修改名字",
        initialValue = userName,
        onConfirm = { userName = it; saveAll(); showNameDialog = false },
        onDismiss = { showNameDialog = false }
    )

    /* 签名 */
    if (showBioDialog) EditTextDialog(
        title = "修改签名",
        initialValue = userBio,
        onConfirm = { userBio = it; saveAll(); showBioDialog = false },
        onDismiss = { showBioDialog = false }
    )

    /* 地区 */
    if (showRegionDialog) EditTextDialog(
        title = "修改地区",
        initialValue = tempRegion,
        onConfirm = { tempRegion = it; saveAll(); showRegionDialog = false },
        onDismiss = { showRegionDialog = false }
    )

    /* 生日 */
    if (showBirthdayDialog) EditTextDialog(
        title = "修改生日",
        initialValue = userBirthday,
        onConfirm = { userBirthday = it; saveAll(); showBirthdayDialog = false },
        onDismiss = { showBirthdayDialog = false }
    )

    /* 身高（转成 String） */
    if (showHeightDialog) EditTextDialog(
        title = "修改身高",
        initialValue = userHeight.toString(),
        onConfirm = {
            it.toIntOrNull()?.let { h ->
                userHeight = h
                saveAll()
            }
            showHeightDialog = false
        },
        onDismiss = { showHeightDialog = false }
    )

    /* 体重（转成 String） */
    if (showWeightDialog) EditTextDialog(
        title = "修改体重",
        initialValue = userWeight.toString(),
        onConfirm = {
            it.toIntOrNull()?.let { w ->
                userWeight = w
                saveAll()
            }
            showWeightDialog = false
        },
        onDismiss = { showWeightDialog = false }
    )

    /* 性别 */
    if (showGenderDialog) SelectOptionDialog(
        title = "选择性别",
        options = listOf("男", "女"),
        selectedOption = tempGender,
        onConfirm = { tempGender = it; saveAll(); showGenderDialog = false },
        onDismiss = { showGenderDialog = false }
    )
}

/* ---------- 通用组件 ---------- */
@Composable
fun ProfileItem2(label: String, value: Any, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .padding(vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(label, style = MaterialTheme.typography.bodyLarge)
        Spacer(Modifier.weight(1f))
        Text(value.toString())
    }
}

@Composable
fun SelectOptionDialog(
    title: String,
    options: List<String>,
    selectedOption: String,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var selected by remember { mutableStateOf(selectedOption) }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column {
                options.forEach { opt ->
                    Row(
                        Modifier
                            .fillMaxWidth()
                            .clickable { selected = opt }
                            .padding(vertical = 8.dp)
                    ) {
                        RadioButton(selected = selected == opt, onClick = { selected = opt })
                        Spacer(Modifier.width(8.dp))
                        Text(opt)
                    }
                }
            }
        },
        confirmButton = { Button(onClick = { onConfirm(selected) }) { Text("确认") } },
        dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }
    )
}

@Composable
fun EditTextDialog(
    title: String,
    initialValue: String,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit
) {
    var textValue by remember { mutableStateOf(initialValue) }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            OutlinedTextField(
                value = textValue,
                onValueChange = { textValue = it },
                singleLine = true,
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = { onConfirm(textValue) })
            )
        },
        confirmButton = { Button(onClick = { onConfirm(textValue) }) { Text("确认") } },
        dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }
    )
}

/* ---------- 网络层 ---------- */
private suspend fun fetchProfileData(userId: Long): Profile? {
        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
        .build()
    return withContext(Dispatchers.IO) {
        try {
            val response = client.newCall(request).execute()
            val body = response.body?.string() ?: return@withContext null
            val json = Gson().fromJson(body, JsonObject::class.java)
            if (json.get("success")?.asBoolean == true) {
                val data = json.getAsJsonObject("data")
                Profile(
                    //id = data.get("id")?.asLong ?: 0L,
                    userId = data.get("userId")?.asLong ?: userId,
                    name = data.get("name")?.asString ?: "用户",
                    des = data.get("des")?.asString ?: "",
                    avatar = data.get("avatar")?.asString, // 头像URL
                    gender = data.get("gender")?.asString ?: "保密",
                    height = data.get("height")?.asDouble ?: 0.0,
                    weight = data.get("weight")?.asDouble ?: 0.0,
                    birthday = data.get("birthday")?.asString ?: "1990-01-01",
                    location = data.get("location")?.asString ?: "未知"
                )
            } else null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

private suspend fun updateProfile(profile: Profile, context: Context) {
        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
    val body = Gson().toJson(profile).toRequestBody(
        "application/json; charset=utf-8".toMediaTypeOrNull()
    )
    val request = Request.Builder()
        .url("${NetworkConfig.BASE_URL}/api/user-profile/save")
        .post(body)
        .build()
    withContext(Dispatchers.IO) {
        try {
            val response = client.newCall(request).execute()
            withContext(Dispatchers.Main) {
                Toast.makeText(
                    context,
                    if (response.isSuccessful) "保存成功" else "保存失败",
                    Toast.LENGTH_SHORT
                ).show()
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "网络错误: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}